package com.vinobase.model.dao;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.vinobase.model.bean.CountryLocal;
import com.vinobase.model.bean.Region;
import com.vinobase.utils.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

@Repository
public class RegionDao {

    @Autowired
    private ObjectifyFactory objectifyFactory;

    public SortedSet<Region> getList(String userId){
        Objectify ofy = objectifyFactory.begin();
        List<Region> regions = ofy.query(Region.class).list();
        SortedSet<Region> res = new TreeSet<Region>();
        for(Region r : regions){
            r.setCountryName(ofy.get(CountryLocal.class, r.getCountry().getId()).getName());
            res.add(r);
        }
        return res;
    }

    public void create(Region region){
        Objectify ofy = objectifyFactory.begin();
        region.setCountry(new Key<CountryLocal>(CountryLocal.class, region.getCountryId()));
        ofy.put(region);
    }

    public Region get(Long regionId){
        Objectify ofy = objectifyFactory.begin();
        Region region = ofy.get(Region.class, regionId);
        if(region == null) {
            throw new ResourceNotFoundException(regionId);
        }
        region.setCountryId(region.getCountry().getId());
        return region;
    }

    public void delete(Long regionId){
        Objectify ofy = objectifyFactory.begin();
        ofy.delete(Region.class, regionId);
    }


}
